﻿using K3Cloud.WebApi.Core.IoC.Cache;
using K3Cloud.WebApi.Core.IoC.DataEntity;
using K3Cloud.WebApi.Core.IoC.Extensions;
using K3Cloud.WebApi.Core.IoC.K3Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Net;

namespace K3Cloud.WebApi.Core.IoC;
/// <summary>
/// K3IOCServiceCollectionExtensions 提供 K3 注入语法糖
/// </summary>
public static class K3IOCServiceCollectionExtensions
{
    internal static K3Config Configs;
    internal static LoginResult LoginResult;
    internal static ICacheService CacheService;
    internal static readonly CookieContainer _cookie = new();
    internal static K3HttpService HttpClient;

    /// <summary>
    /// K3注入语法糖
    /// </summary>
    public static IServiceCollection AddK3Sugar(this IServiceCollection services, K3Config config)
    {
        InitializeServices(services, config);
        return services;
    }

    /// <summary>
    /// lambda 表达式来设置K3Config
    /// </summary>
    public static IServiceCollection AddK3Sugar(this IServiceCollection services, Action<K3Config> setupAction)
    {
        if (setupAction == null) throw new ArgumentNullException(nameof(setupAction));
        K3Config k3Config = new();
        setupAction(k3Config);
        return services.AddK3Sugar(k3Config);
    }

    /// <summary>
    /// 读取appsettings.json文件K3CLOUDCONFIG节点配置
    /// </summary>
    public static IServiceCollection AddK3Sugar(this IServiceCollection services)
    {
        IConfigurationRoot builder = new ConfigurationBuilder()
            .AddInMemoryCollection()
            .AddJsonFile("appsettings.json", optional: false)
            .Build();

        IConfigurationSection k3CloudConfig = builder.GetSection("K3CLOUDCONFIG");
        if (k3CloudConfig == null) throw new ArgumentNullException(nameof(k3CloudConfig));
        K3Config k3Config = builder.GetValue<K3Config>("K3CLOUDCONFIG") ?? builder.GetSection("K3CLOUDCONFIG").GetChildren().FirstOrDefault().Get<K3Config>();
        return services.AddK3Sugar(k3Config);
    }
    /// <summary>
    /// 初始化服务
    /// </summary>
    private static void InitializeServices(IServiceCollection services, K3Config config)
    {
        Configs = config ?? throw new ArgumentNullException(nameof(config));
        ConfigureK3Config(services, config); // 因为HttpClient用到了K3Config, 所以要先配置K3Config
        services.AddDefaultHttpClient(_cookie);
        var scope = services.BuildServiceProvider();
        CacheService = scope.GetService<ICacheService>() ?? AddDefaultCacheService(services);
        HttpClient = scope.GetService<K3HttpService>();
    }
    /// <summary>
    /// 添加默认缓存服务
    /// </summary>
    private static ICacheService AddDefaultCacheService(IServiceCollection services)
    {
        services.AddSingleton<ICacheService, MemoryCacheService>();
        using var innerScope = services.BuildServiceProvider().CreateScope();
        return innerScope.ServiceProvider.GetService<ICacheService>();
    }
    /// <summary>
    /// 配置K3Config, 用于依赖注入
    /// </summary>
    private static void ConfigureK3Config(IServiceCollection services, K3Config config)
    {
        services.Configure<K3Config>(cfg =>
        {
            cfg.AcctId = config.AcctId;
            cfg.AppID = config.AppID;
            cfg.AppSecret = config.AppSecret;
            cfg.UserName = config.UserName;
            cfg.Password = config.Password;
            cfg.LCID = config.LCID;
            cfg.ServerHost = config.ServerHost;
            cfg.ConnectionValidTime = config.ConnectionValidTime;
        });
    }
}

